from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers
from django_redis import get_redis_connection

from goods.models import SKU
from goods.search_indexes import SKUIndex
from goods.utils import PageNum


class SKUSSerialziers(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = '__all__'


class SKUSearchSeializer(HaystackSerializer):
    object = SKUSSerialziers(read_only=True)

    class Meta:
        index_classes = [SKUIndex]
        fields = ('text', 'object')


class SKUHistorySerialzier(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    # 判断商品是否存在
    def validate(self, attrs):
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        return attrs

    def create(self, validated_data):
        # 获取当前用户
        user=self.context['request'].user
        sku_id=validated_data['sku_id']
        # 1、建立缓存对象
        conn=get_redis_connection('history')
        # 2、判断当前sku_id是否存在列表
        pl=conn.pipeline()
        pl.lrem('history_%s'%user.id,0,sku_id)
        # 3、写入缓存
        pl.lpush('history_%s'%user.id,sku_id)
        # 4、控制数量
        pl.ltrim('history_%s'%user.id,0,4)
        pl.execute()

        return validated_data



